package com.sgj.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.AuthServerConstant;
import com.sgj.common.enums.BizCodeEnum;
import com.sgj.common.utils.R;
import com.sgj.common.vo.MemberRegistVo;
import com.sgj.common.vo.MemberRespVo;
import com.sgj.common.vo.UserLoginVo;
import com.sgj.gulimall.auth.feign.MemberFeignService;
import com.sgj.gulimall.auth.feign.ThirdPartFeignService;
import com.sgj.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/2 13:25
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登陆
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            // 登陆成功,将用户数据存入session
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
        attributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (Objects.isNull(attribute)) {
            return "login";
        }
        return "redirect:http://gulimall.com";
    }

    /**
     * 注册
     * @param vo
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping("/register")
    public String register(@Validated UserRegistVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            // model.addAttribute("errors", errors);
            attributes.addFlashAttribute("errors", errors);
            // 校验出错，转发到注册页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotBlank(redisCode)) {
            // 截取出存在redis中的验证码，与用户输入进行对比
            if (code.equals(redisCode.split("_")[0])) {
                // 删除 redis 验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码正确， 调用远程服务进行注册
                R r = memberFeignService.register(changeVo(vo));
                if (r.getCode() == 0) {
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                return checkCode(attributes);
            }
        } else {
            return checkCode(attributes);
        }
    }

    /**
     * 发送验证码(有效时间为1分钟)
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        // TODO 接口防刷

        // 防止有人恶意请求验证码发送
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotBlank(redisCode)) {
            // 验证码存入redis的时间
            long redisTime = Long.parseLong(redisCode.split("_")[1]);
            if ((System.currentTimeMillis() - redisTime) < 60000) {
                // 验证码发送时间未到60s，不能重新发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        // 随机六位验证码
        String code = String.valueOf(Math.random()).substring(2, 8);
        // 加上当前系统时间存入redis，判断是否为一分钟内发出的验证码
        String codeInRedis = code + "_" + System.currentTimeMillis();
        // 将验证码存入redis,10分钟有效
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeInRedis, 10, TimeUnit.MINUTES);

        thirdPartFeignService.sendSmsCode(phone, code, "1");
        return R.ok();
    }

    /**
     * 校验验证码
     * @param attributes
     * @return
     */
    private String checkCode(RedirectAttributes attributes) {
        Map<String, String> errors = new HashMap<>();
        errors.put("code", "验证码错误");
        attributes.addFlashAttribute("errors", errors);
        // 校验出错，转发到注册页面
        return "redirect:http://auth.gulimall.com/reg.html";
    }

    private MemberRegistVo changeVo (UserRegistVo vo) {
        MemberRegistVo vo1 = MemberRegistVo.builder()
                .userName(vo.getUserName())
                .password(vo.getPassword())
                .phone(vo.getPhone())
                .build();
        return vo1;
    }
}